package top.codedance.iotp.registy.net.handle.action;

import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.enums.HttpStatus;
import top.codedance.iotp.registy.RegistryApplication;
import top.codedance.iotp.registy.net.handle.AdapterController;
import org.apache.log4j.Logger;

import java.util.Date;

public class VictoryController extends AdapterController {
    private static Logger logger = RegistryApplication.getLogger(VictoryController.class);

    @Override
    public String doSubHandler(JSONObject body) {
        if(RegistryApplication.isElectioning) {
            RegistryApplication.masterHost = body.getString("masterHost");
            RegistryApplication.isMaster = false;
            RegistryApplication.isElectioning = false;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("ack", true);
            logger.debug("收到确认主权");
            Date d = new Date();
            RegistryApplication.syncLastTimestamp = d.getTime();
            return okResponse(jsonObject);
        }else{
            return errResponse(HttpStatus.SERVICE_UNAVAILABLE.getCode(), "Election is ended");
        }
    }
}
